<?php

namespace app\admin\service;

use app\admin\model\Role as model;
use app\admin\model\Menu;
use app\admin\model\Admin;
use app\lib\exception\Admin as AdminException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Role
{
    /**
     * @param $ids
     * @return array
     * @throws AdminException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    static function getRole($ids): array
    {
        if (empty($ids)) {
            throw new AdminException(['msg' => '角色错误']);
        }
        $where = [];
        $where[] = ['id', 'in', $ids];
        $stars = (new model)->field('role_name,menu_id')->where($where)->select()->toArray();
        if (empty($stars)) throw new AdminException();

        return $stars;
    }

    /**
     * @return array
     * @throws AdminException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    static function getList(): array
    {
        $stars = (new model)->field('id,role_name')->select()->toArray();
        if (empty($stars)) throw new AdminException();

        return $stars;
    }

    /**
     * @param $param
     * @return array
     * @throws AdminException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    static function getLists($param): array
    {
        if (empty($param)) throw new AdminException();
        $where = [];
        $list = [];
        if (!empty($param['role_name'])) {
            $where[] = ['role_name', 'like', '%' . $param['role_name'] . '%'];
        }
        $total = (new Model)->where($where)->count();
        if ($total > 0) {
            $list = (new Model)->field('id,role_name,is_enable,menu_id,enable_time,create_time')->where($where)->page($param['pageNum'], $param['pageSize'])->select();
            $list = $list->toArray();
            foreach ($list as &$item) {
                if ($item['is_enable'] != 1) {
                    unset($item['enable_time']);
                }
//                $permissions = (new Menu)->where([['id', 'in', $item['menu_id']]])->column('title');
//                $item['permissions'] = implode(' | ', $permissions);
            }
//            var_dump($list);exit();
        }

//        $list = Db::name('role')->where($where)->paginate($param['pageSize'], false)->each(function ($item, $key) {
//            $permissions = Db::name('route_resource')->where([['id', 'in', $item['route_resource_ids']]])->column('title');
//            $item['permissions'] = implode(' | ', $permissions);
//            return $item;
//        });
//        $data = $list;
        return ['data' => $list, 'total' => $total];
    }

    /**
     * @param $param
     * @return array
     * @throws AdminException
     */
    static function getDetail($param): array
    {
        if (empty($param)) throw new AdminException();
        $where = [];
        $where[] = ['id', '=', $param['id']];
        $res = (new Model)->where($where)->findOrEmpty();
        if ($res->isEmpty()) {
            throw new AdminException(['msg' => '数据不存在']);
        }

        $res['menuItems'] = (new Menu)->whereIn('id', $res['menu_id'])->fetchSql(false)->select()->toArray();
        $res['menuIds'] = explode(',', $res['menu_id']);
        $res['value'] = $res['id'];
        $res['label'] = $res['id'];

        return $res->toArray();
    }

    /**
     * @param $param
     * @return bool
     * @throws AdminException
     */
    static function doEdit($param): bool
    {
        $exist = (new Model)->where(
            [
                ['role_name', '=', $param['role_name']],
                ['id', '<>', $param['id']],
            ]
        )->findOrEmpty();
        if (!$exist->isEmpty()) {
            if (empty($param)) throw new AdminException(['msg' => '角色名称已存在']);
        }
        if ($param['is_enable'] == 1) {
            $param['enable_time'] = date('Y-m-d H:i:s');
        } else {
            $param['enable_time'] = null;
        }
        $param['update_time'] = date('Y-m-d H:i:s');
        $res = (new Model)->update($param, ['id' => $param['id']], ['role_name', 'is_enable', 'menu_id', 'enable_time']);
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $param
     * @return bool
     * @throws AdminException
     */
    static function doAdd($param): bool
    {
        if (empty($param)) throw new AdminException(['msg' => '数据缺失']);
        if (Model::getByRoleName($param['role_name'])) {
            throw new AdminException(['msg' => '角色名称已存在']);
        }

        $data = [];
        $data['role_name'] = $param['role_name'];
        $data['menu_id'] = $param['menu_id'];
        $data['is_enable'] = $param['is_enable'];
        if ($param['is_enable'] == 1) {
            $data['enable_time'] = date('Y-m-d H:i:s');
        } else {
            $data['enable_time'] = null;
        }
        $data['create_time'] = date('Y-m-d H:i:s');
        $res = (new Model)->save($data);
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $ids
     * @return bool
     * @throws AdminException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    static function doDelete($ids): bool
    {
        if (empty($ids)) throw new AdminException(['msg' => '数据缺失']);
        $Admin = new Admin();
        //查找是否有管理员使用这个角色则提示不能删除
        $admins = $Admin->column('role_ids');
//        var_dump($admins);exit();
        $is_setting = false;
        $arr = [$ids];
        foreach ($admins as $key => $value) {
            if (count(array_intersect($arr, [$value])) > 0) {
                $is_setting = true;
                break;
            }
        }
        if ($is_setting) {
            throw new AdminException(['msg' => '删除的角色中有角色已被使用，不能删除']);
        }

        $find = (new Model)::find($ids);
        $res = $find->delete();
//        $find = (new model)::onlyTrashed()->find($ids);
//        $res = $find->restore();
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }
}